package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishNotFoundException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;


@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private FlavorMapper flavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null) {
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });
            flavorMapper.insert(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 开启分页功能，根据传入的页码和页面大小查询菜品数据
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        // 调用 DishMapper 的 page 方法执行查询，参数为 dishPageQueryDTO
        Page<DishVO> p = dishMapper.page(dishPageQueryDTO);

        // 构造返回结果 PageResult，包含总记录数和当前页数据集合
        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        //在售状态下不能删除菜品
        for (Long id : ids) {
            DishVO dish = dishMapper.getByIdWithFlavor(id);
            if (dish.getStatus() == 1) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //关联套餐的菜品不能删除
        for (Long id : ids) {
            Integer count = setmealMapper.countByDishId(id);
            if (count > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        dishMapper.deleteById(ids);

        //删除菜品关联的口味
        for (Long id : ids) {
            flavorMapper.deleteById(id);
        }


    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO = dishMapper.getByIdWithFlavor(id);
        //根据菜品的id查询口味
        if (dishVO == null) {
            throw new DishNotFoundException("未找到ID为 " + id + " 的菜品");
        }
        List<DishFlavor> flavors = flavorMapper.getByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */

    //添加事务管理
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null) {
            //先删除原来的口味
            flavorMapper.deleteById(dishDTO.getId());
            //如果传入的口味的长度为0，则直接返回
            if (flavors.isEmpty()) return;
            //再添加新的口味
            flavors.forEach(flavor -> {
                flavor.setDishId(dishDTO.getId());
            });

            flavorMapper.insert(flavors);
        }
    }

    /**
     * 根据id修改菜品
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     * @return
     */
    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {
        List<DishVO> dishVOS = dishMapper.getByCategoryId(categoryId);
        return dishVOS;
    }



    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors =flavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
